#!/usr/bin/bash
set -e

# 获取安装版本
echo -n "install zookeeper version(3.9.0): "
read version

# 构建下载路径
download_path=""
hosts=(
    "https://mirrors.tuna.tsinghua.edu.cn/apache/"
    "https://archive.apache.org/dist/"
)
path="zookeeper/zookeeper-${version}/apache-zookeeper-${version}-bin.tar.gz"
for host in "${hosts[@]}"; do
	  response=$(curl -sI "${host}${path}")
    if echo "$response" | grep -q "HTTP/.* 200"; then
        download_path="${host}${path}"
        break
    fi
done
binary_name=`basename ${download_path}`

package_dir="/srv/package/"
install_dir="/srv/software/"
custom_env_file="/etc/profile.d/custom_env.sh"

# 创建存放目录，然后下载、安装、改名
mkdir -p ${package_dir} ${install_dir}
wget ${download_path} -P ${package_dir}
tar xf ${package_dir}${binary_name} -C ${install_dir}
mv ${install_dir}apache-zookeeper-${version}-bin ${install_dir}zookeeper-${version}

# 添加环境变量
software_name=$(ls -l ${install_dir} |grep zookeeper |grep ${version} |awk '{print $9}')
software_home=${install_dir}${software_name}
cat >> ${custom_env_file} <<-EOF
export ZOOKEEPER_HOME=${software_home}
export PATH=\$ZOOKEEPER_HOME/bin:\$PATH
EOF
source /etc/profile

# 配置 zoo.cfg
cat > ${software_home}/conf/zoo.cfg <<-EOF
tickTime=2000
initLimit=10
syncLimit=5
dataDir=${software_home}/data
clientPort=2181
autopurge.snapRetainCount=3
autopurge.purgeInterval=72
server.1=node1:2888:3888
server.2=node2:2888:3888
server.3=node3:2888:3888
EOF

# 配置 myid
mkdir -p ${software_home}/data
echo "1" > ${software_home}/zkdata/myid

# 分发配置，并修改 myid
scp -r ${software_home} node2:${install_dir}
scp -r ${software_home} node3:${install_dir}

scp ${custom_env_file} node2:${custom_env_file}
scp ${custom_env_file} node3:${custom_env_file}

ssh root@node3 "echo "2" > ${software_home}/data/myid"
ssh root@node3 "echo "3" > ${software_home}/data/myid"

# 群起脚本
cat > /usr/local/bin/zookeeper-daemon.sh <<EOF
#!/bin/bash
for host in node1 node2 node3
do
    echo "===== zookeeper \$host \$1 ====="
    ssh \$host "source /etc/profile;${software_home}/bin/zkServer.sh \$1"
done
EOF

# 添加执行权限
chmod 755 /usr/local/bin/zookeeper-daemon.sh

# 安装成功提示
echo "Successfully installed zookeeper..."